package com.laboratory.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by 30868 on 2019/04/10.
 * 构建一个线程池
 */
public class TaskEngine {


    private static TaskEngine instance = new TaskEngine();
    public static TaskEngine getInstance(){
        return  instance;
    }

    private ThreadPoolExecutor executor;

    public TaskEngine() {
        executor = new ThreadPoolExecutor(1, 10, 8000L,
                TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() {
            final AtomicInteger threadNumber = new AtomicInteger();
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(Thread.currentThread().getThreadGroup(),r, "TaskEngine--Pool-"+threadNumber,0);
                thread.setDaemon(true);
                if (thread.getPriority() != Thread.NORM_PRIORITY){
                    thread.setPriority(Thread.NORM_PRIORITY);
                }
                return thread;
            }
        });
    }

    public Future<?> submit(Runnable task){
        return executor.submit(task);
    }

    public Future<?> submit(Callable task){
        return executor.submit(task);
    }
}
